package com.mediacloud.app.newsmodule.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.view.WindowManager;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.eventTrack.CDPTrackReportManager;
import com.eventTrack.TXReportManager;
import com.jaeger.library.StatusBarUtil;
import com.mediacloud.app.assembly.util.FunKt;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.fbnavsk.SecondNav;
import com.mediacloud.app.model.activity.BaseBackActivity;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.model.utils.AppModuleUtils;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.adaptor.AdapterPreInflateHelper;
import com.mediacloud.app.newsmodule.fragment.BaseNewsListFragmentX;
import com.mediacloud.app.newsmodule.fragment.ExtendKt;
import com.mediacloud.app.newsmodule.fragment.newslist.NestedNav;
import com.mediacloud.app.newsmodule.model.NavigateListReciver;
import com.mediacloud.app.newsmodule.utils.NavigateDataInvoker;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig.FeatureModule.BigModule;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig.ServerAppConfigInfo.NavigateBarStyle;
import com.mediacloud.app.reslib.enums.Navigate;
import com.mediacloud.app.reslib.enums.XKey;
import com.politics.fragment.NeedToAskingPoliticsFragment;
import com.politics.model.PoliticsConstKt;
import com.utils.UriTool;

import java.util.ArrayList;

/**
 * 带导航的Activity
 * 根据外部传入的导航id去取相应的子导航 然后给TableCatalogItemsFragment让他自己去初始化相应的子导航页面
 * //APP外打开一个导航
 * appfactory://包名/navigate?id=导航的id&title=顶栏显示的标题&showSecond=布尔值是否请求显示该id下的二级导航
 *
 * @author x
 */
@SuppressWarnings("ALL")
public class NavigateActivity extends BaseBackActivity implements DataInvokeCallBack<NavigateListReciver> {
    //政策解读页面 是否 在展示
    public static final boolean isOnPolicyInterpretation=false;
    protected Fragment navigateFragment;
    protected View mLoadingView, mEmptyContent;
    public static final String Catalogs = SecondNav.Catatlogs;
    CatalogItem catalog;
    protected ArrayList<CatalogItem> catalogs = new ArrayList<CatalogItem>();
    NavigateDataInvoker navigateDatainvoker;
    boolean needLoadSecondBg = false;
    Navigate navigate = null;
    boolean isUriArgs = false;
    boolean showSecondTag = false;
    String intentTitle = "";
    int index = -1;
    private String searchId;
    private boolean is_jump_this;//判断是否是NavigateActivty跳自己
    private int nid;
    private  String CDPcatname;
    private  String CDPcatid;
    private  String CDPCurrentPagName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        AdapterPreInflateHelper.preSwitch = false;

        mLoadingView = Utility.findViewById(mRootView, R.id.mLoadingView);
        mEmptyContent = Utility.findViewById(mRootView, R.id.mEmptyContent);
        CDPcatname = CDPTrackReportManager.getInstance().getCatName();
        CDPcatid = CDPTrackReportManager.getInstance().getCatId();
        CDPCurrentPagName = CDPTrackReportManager.getInstance().getCurrentPageName();

        //		initNavigateChild();
        nid = getIntent().getIntExtra("nid", 0);
        if (getIntent().getData() != null) {
            isFromH5OpenToReStart = UriTool.INSTANCE.isFromH5OpenToReStart(this, getIntent().getData());
            try {
                intentTitle = getIntent().getData().getQueryParameter("title");
                setTitle(intentTitle);
                String id = getIntent().getData().getQueryParameter("id");
                searchId = getIntent().getData().getQueryParameter("searchId");
                String navname = getIntent().getData().getQueryParameter("navname");
                String selected_index = getIntent().getData().getQueryParameter("selected_index");
                if (selected_index != null) {
                    index = Integer.parseInt(selected_index);
                }
                showSecondTag = Boolean.valueOf(getIntent().getData().getQueryParameter("showSecond"));
                catalog = new CatalogItem();
                catalog.setCatalog_type(String.valueOf(getIntent().getData().getQueryParameter("type")));
                catalog.setCatid(id);
                catalog.setCatname(TextUtils.isEmpty(navname) ? intentTitle : navname);
                navigate = new Navigate();
                navigate.setCategory(catalog.getCatalog_type());
                navigate.name = navigate.sname = TextUtils.isEmpty(navname) ? intentTitle : navname;
                navigate.id = id;
                catalog.setNavigate(navigate);
                isUriArgs = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            catalog = getIntent().getParcelableExtra(Catalogs);
            showSecondTag = getIntent().getBooleanExtra("showSecondTag", false);
            intentTitle = getIntent().getStringExtra("title");
            navigate = getIntent().getParcelableExtra("navigate");
            if (catalog != null) {
                catalog.setNavigate(navigate);
            }
        }
        try {
            if (catalog!=null&&("1332" .equals(catalog.getId()) ||"1958".equals(catalog.getId()))  ) {
                TXReportManager.getInstance().activity_query();
            }
        }catch (Exception e){

        }

        if ("政策解读".equals(intentTitle) || "阅读政策".equals(intentTitle)) {
            isOnPolicyInterpretation = true;
        }
        TXReportManager.getInstance().setMoreTitle(intentTitle);
        is_jump_this = getIntent().getBooleanExtra(XKey.IS_JUMP_NAVIGETE, false);

        String catalog_type = catalog != null ? catalog.getCatalog_type() : "";
        if (BigModule.OBJECT_POLITICS_NAV.equals(catalog_type)) {
            setTitle(intentTitle);
        } else if (!TextUtils.isEmpty(intentTitle)) setTitle(intentTitle);
        else if (catalog != null) setTitle(catalog.getCatname());
        if (catalog != null) {
            navigateDatainvoker = new NavigateDataInvoker(this);
            navigateDatainvoker.invokeChildNavigate(catalog.getCatid(), this, isUriArgs);
        }
        if (mTitlebar_name != null) {
            if (mTitlebar_name.getText().toString().equals("行军百里")) {
                TXReportManager.getInstance().app_jhapp_explore_func_ck("行军百里", "行军百里", "成功", "成功");
            }
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mTitlebar_name != null) {
            TXReportManager.getInstance().getCurrentPageName(mTitlebar_name.getText().toString());
        }
    }

    /**
     * 我要问政界面单独处理
     */
    private void setPoliticsTitleBar() {
        if (navigateFragment instanceof NeedToAskingPoliticsFragment) {
            StatusBarUtil.setColorNoTranslucent(this, Color.WHITE);
            mTitileBar.setBackgroundColor(getResources().getColor(R.color.white));
            mTitlebar_name.setTextColor(getResources().getColor(R.color._333));
            setBackText("取消", getResources().getColor(R.color._666));
            setMoreText("提交", getResources().getColor(R.color._666));
            mBackText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
            mMoreText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (FunKt.isFastClick())
                        ((NeedToAskingPoliticsFragment) navigateFragment).onSubmit();

                }
            });
            mTop_back.setVisibility(View.GONE);
            mMoreText.setVisibility(View.VISIBLE);
            mBackText.setVisibility(View.VISIBLE);
        }
    }

    public String getIntentTitle() {
        return intentTitle;
    }

    @Override
    public int getLayoutResID() {
        return R.layout.aappfactory_navigate_activity;
    }

    protected void initNavigateChild() {
        navigateFragment = new NestedNav();
        Bundle arguments = new Bundle();
        if (showSecondTag) {
            arguments.putParcelableArrayList(Catalogs, catalogs);
        } else {
            //bug  Android端，组件绑定导航，关闭二级导航，会重复显示绑定的导航  https://zentao.chinamcloud.com/zentao/bug-view-21741.html
            ArrayList<CatalogItem> emptyCatalogItem = new ArrayList<CatalogItem>();
            arguments.putParcelableArrayList(Catalogs, emptyCatalogItem);
        }
        arguments.putSerializable("navigate", navigate);
        arguments.putBoolean(Intent.ACTION_INSERT, true);
        //if(index!=-1 && index<catalogs.size()){
        // catalogs.get(index).setSecond_is_home(1);
        arguments.putInt("selectIndex", index);
        arguments.putString("searchId", searchId);//这样传hqyfragment不知道为啥会走两次，第二次就是null,改为下面方式存
        ExtendKt.setSearchId(searchId);
        // }
        navigateFragment.setArguments(arguments);//提前设置  不然下面去设置会覆盖值
        if (catalogs.size() == 1) {
            //只有一个 并且 导航 是链接等这几类的情况 下才需要加载第二个背景图
            String type = catalogs.get(0).getCatalog_type();
            if (BigModule.Link.equals(type) || BigModule.H5Broke.equals(type) || BigModule.ScoreMall.equals(type)) {
                needLoadSecondBg = true;
                loadSecondSkinBg();
            }
            //不取二级导航  直接加载
            Fragment fragment = AppModuleUtils.getViewContentFragment(this, catalog);
            if (fragment != null) {
                navigateFragment = fragment;
            }
        }
        if (nid != 0) {
            if (navigateFragment instanceof BaseNewsListFragmentX) {
                ((BaseNewsListFragmentX) navigateFragment).nid = nid;
            } else if (navigateFragment instanceof SecondNav) {
                ((SecondNav) navigateFragment).setMNid(nid);
            }
        }
        setPoliticsTitleBar();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.navigateContent, navigateFragment);
        transaction.show(navigateFragment);
        transaction.commitNowAllowingStateLoss();
        mLoadingView.setVisibility(View.GONE);
    }

    protected boolean needLoadTopSecondBgSkin() {
        return needLoadSecondBg && super.subClassgetNeedTopSecondBgSkin();//"1".equals(getResources().getString(R.string.need_load_second_topskin));
    }

    @Override
    protected NavigateBarStyle getNewsDetailNavigateBarStyle() {
        if (needLoadSecondBg) {
            return AppFactoryGlobalConfig.getAppServerConfigInfo(this).getLinkNewsBar();
        }
        return null;
    }

    @Override
    public void finish() {
        if ("政策解读".equals(intentTitle) || "阅读政策".equals(intentTitle)) {
            isOnPolicyInterpretation = false;
        }
        super.finish();
        if (navigateDatainvoker != null) navigateDatainvoker.destory();
        navigateDatainvoker = null;
        if (catalogs != null) catalogs.clear();
        catalogs = null;
    }

    @Override
    public void success(NavigateListReciver data) {
        if (isFinishing() || isDestroyed()) {
            return;
        }
        if (isUriArgs) {
            if (data.catalogs.size() > 0) {
                CatalogItem removed = data.catalogs.remove(0);
                String title = removed.getCatname();
                catalog = removed;
                navigate = catalog.getNavigate();
                //这去单独判断一下是不是对象问题 如果是 并且要先打开选择页面 那么就把取到的里面的导航列表类型设置成问政对象列表的类型
                if (BigModule.OBJECT_POLITICS_NAV.equals(catalog.getCatalog_type()) || BigModule.Publish_Politics.equals(catalog.getCatalog_type())) {
                    //问政的时候是不显示二级导航的
                    showSecondTag = false;
                    if (catalog.is_select_politics_spider == 1) {
                        catalog.setCatalog_type(BigModule.Politics_Choose_Object);
                        navigate.setCategory(BigModule.Politics_Choose_Object);
                        if (catalog.getPolitics_type() == PoliticsConstKt.TYPE_SHUJI_XINXIANG || catalog.getPolitics_type() == PoliticsConstKt.TYPE_ZHUANYUAN_XINXIANG) {
                            if (catalog.getPolitics_type() == PoliticsConstKt.TYPE_SHUJI_XINXIANG) {
                                setTitle("给书记写信");
                            } else {
                                setTitle("给专员写信");
                            }
                        } else {
                            if (intentTitle == null)
                                setTitle(getResources().getString(R.string.politics_objects, catalog.getPolitics_identification()));
                        }
                    } else {
                        if (catalog.getPolitics_type() == PoliticsConstKt.TYPE_SHUJI_XINXIANG || catalog.getPolitics_type() == PoliticsConstKt.TYPE_ZHUANYUAN_XINXIANG) {
                            if (catalog.getPolitics_type() == PoliticsConstKt.TYPE_SHUJI_XINXIANG) {
                                setTitle("给书记写信");
                            } else {
                                setTitle("给专员写信");
                            }
                        } else {
                            if (intentTitle == null)
                                setTitle(getResources().getString(R.string.iwant_ask_politic, catalog.getPolitics_identification()));
                        }
                        if (mTitlebar_name != null) {
                            mTitlebar_name.getPaint().setFakeBoldText(false);
                            mTitlebar_name.setIncludeFontPadding(false);
                            mTitlebar_name.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.dimen20sp));
                        }
                    }
                    //全部把导航清了 就只显示一个叫他选择对象的那个列表
                    data.catalogs.clear();
                    catalogs.clear();
                    data.catalogs.add(catalog);
                } else {
                    if (TextUtils.isEmpty(title) == false) {
                        catalog.setCatname(title);
                        navigate.setName(title);
                        navigate.setSname(title);
                        navigate.setSecond_navigate(removed.getNavigate().getSecond_navigate());
                    }
                    if (catalog.getIs_second_navigate() == 1 || showSecondTag) {
//						data.catalogs.clear();
                        catalogs.clear();
                        if (!isUriArgs) data.catalogs.add(0, catalog);
                    }
                }
            }
        }
        catalogs.addAll(data.catalogs);
        initNavigateChild();
    }


    public void refreshNavBarColor(int color) {
        mTitileBar.setBackgroundColor(color);
//		refreshStatusBarColor();
        StatusBarUtil.setColorNoTranslucent(this, color);
    }


    @Override
    public void fault(Object data) {
        if (isFinishing() || isDestroyed()) {
            return;
        }
        initNavigateChild();
    }

    /**
     * 主要是导航里头有全屏的那种东西的
     *
     * @return
     */
    @Override
    public int getStatusBarColor() {
        final int flag = WindowManager.LayoutParams.FLAG_FULLSCREEN;
        if ((getWindow().getAttributes().flags & flag) == flag) {
            return Color.TRANSPARENT;
        }
        return super.getStatusBarColor();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CDPTrackReportManager.getInstance().setCatName(CDPcatname);
        CDPTrackReportManager.getInstance().setCatId(CDPcatid);
        CDPTrackReportManager.getInstance().setCurrentPageName(CDPCurrentPagName);
        if ("政策解读".equals(intentTitle) || "阅读政策".equals(intentTitle)) {
            isOnPolicyInterpretation = false;
        }
        if (!is_jump_this) {
            TXReportManager.getInstance().clearThirdAndFourTabInfo();
        }
        TXReportManager.getInstance().setMoreTitle("");
        ExtendKt.setSearchId(null);
    }
}